// $codepro.audit.disable
package edu.gatech.oad.cyberdoc.view.invoice;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JLabel;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import edu.gatech.oad.cyberdoc.view.ApplicationPanel;

public class InvoicePanel extends ApplicationPanel {

	/**
	 * The logger for this class.
	 */
	private static final Logger LOG;

	private List<InvoiceButton> added;

	static {
		LOG = Logger.getLogger("edu.gatech.oad.cyberdoc.presenter.Presenter");
	}

	/**
	 * Create the panel.
	 */
	public InvoicePanel() {
		setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));

		JLabel lblViewInvoice = new JLabel("View Invoice");
		lblViewInvoice.setFont(new Font("Lucida Grande", Font.BOLD, 14));
		add(lblViewInvoice);

		Component rigidArea = Box.createRigidArea(new Dimension(0, 20));
		add(rigidArea);

		added = new ArrayList<InvoiceButton>();
	}

	@Override
	public void show(JSONObject response) {
		try {
			if (response.getString("action").equals("view_invoices")) {
				for (InvoiceButton button : added) {
					remove(button);
				}

				JSONArray invoices = response.getJSONArray("invoices");

				for (int i = 0; i < invoices.length(); i++) {
					JSONObject invoice = invoices.getJSONObject(i);
					int id = invoice.getInt("id");
					String patient = invoice.getJSONObject("patient")
							.getString("username");
					Date date = new Date(invoice.getLong("date"));

					InvoiceButton button = new InvoiceButton(id, patient, date);
					add(button);
					added.add(button);
				}

				validate();
			} else {
				JSONObject invoice = response.getJSONObject("invoice");
				new ViewInvoiceDialog(invoice);
			}
		} catch (JSONException e) {
			LOG.log(Level.SEVERE, "Unexpected exception", e);
		}
	}
}
